package com.xxx.test;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;

@WebServlet("/huanshu")
public class huanshu extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id=new String(request.getParameter("id").getBytes("iso-8859-1"),"UTF-8");
        try {
            // 加载数据库驱动，注册到驱动管理器
            Class.forName("com.mysql.jdbc.Driver");
            // 数据库连接字符串
            String url = "jdbc:mysql://localhost:3306/java_text";
            // 数据库用户名
            String usename = "root";
            // 数据库密码
            String psw = "123456";
            // 创建Connection连接
            Connection conn = DriverManager.getConnection(url,usename,psw);
            // 判断 数据库连接是否为空
            if(conn != null){
                int userid = (int) request.getSession().getAttribute("id");
                String sql="delete ub from user_book ub left join books b on ub.bid=b.id where b.id="+id+" and ub.uid="+userid;
                String sql2="update books set bSum = bSum+1 where id="+id;
                Statement stmt = conn.createStatement();
                stmt.executeUpdate(sql);
                stmt.executeUpdate(sql2);
                request.getRequestDispatcher("showBorrow").forward(request,response);
                conn.close();
            }else{
                // 输出连接信息
                request.setAttribute("msg","连接数据库失败");

            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

